<template>
  <div class="app-container">
    <el-container>
      <el-main style="padding: 0 10px">
        <el-splitter>
          <el-splitter-panel>
            <el-card shadow="never">
              <div class="search-bar">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                  <el-form-item prop="keywords" :label="$t('common.keywords')">
                    <el-input
                      v-model="queryParams.keywords"
                      :placeholder="
                        $t('visitor.name') + ', ' + $t('visitor.email') + ', ' + $t('visitor.phone')
                      "
                      clearable
                      @keyup.enter="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="search" @click="handleQuery">
                      {{ $t("common.search") }}
                    </el-button>
                    <el-button icon="refresh" @click="handleResetQuery">
                      {{ $t("common.reset") }}
                    </el-button>
                    <el-button v-if="false" type="info" @click="handleShowDrawer">
                      {{ $t("location.filter") }}
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-table
                ref="dataTableRef"
                v-loading="loading"
                :data="list"
                highlight-current-row
                stripe
              >
                <el-table-column :label="$t('visitor.name')" prop="visitorName" />
                <el-table-column :label="$t('visitor.email')" prop="email" />
                <el-table-column :label="$t('visitor.dept')" align="center" prop="deptName" />
                <el-table-column :label="$t('visitor.purpose')" align="center" prop="purposeName" />
                <el-table-column :label="$t('visitor.status')" align="center" prop="status">
                  <template #default="scope">
                    <el-tag v-if="scope.row.status === 0" type="info">
                      {{ $t("visitor.bindStatus.0") }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === 1" type="primary">
                      {{ $t("visitor.bindStatus.1") }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === 2" type="danger">
                      {{ $t("visitor.bindStatus.2") }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column :label="$t('visitor.actInAt')" prop="actInAt">
                  <template #default="scope">
                    {{
                      scope.row.actInAt != null
                        ? dayjs(scope.row.actInAt).format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}

                    {{
                      scope.row.actOutAt != null
                        ? " / " + dayjs(scope.row.actOutAt).format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column :label="$t('visitor.tagNo')" align="center" prop="tagNo" />
                <el-table-column :label="$t('visitor.opName')" align="center" prop="opName" />
                <el-table-column
                  :label="$t('visitor.currentVisitLocation')"
                  prop="currentVisitLocation"
                  width="200"
                >
                  <template #default="scope">
                    <div v-if="scope.row.currentLocationName != null">
                      <div v-if="locationMap?.get(scope.row.currentLocationId) == 1">
                        <el-tag type="danger">
                          <el-icon color="red"><WarnTriangleFilled /></el-icon>
                          {{ scope.row.currentLocationName }} ({{ t("location.isForbid") }})
                        </el-tag>
                      </div>
                      <el-tag v-else type="success">{{ scope.row.currentLocationName }}</el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" :label="$t('common.action')">
                  <template #default="scope">
                    <el-icon size="25" @click="showMovedLine(scope.row.id)">
                      <LocationInformation />
                    </el-icon>
                    <el-button
                      v-if="scope.row.status == 1"
                      v-hasPerm="'visitor:unbind_tag'"
                      type="info"
                      size="small"
                      link
                      icon="Finished"
                      @click="handleLeft(scope.row.id)"
                    >
                      {{ $t("visitor.unBindTag") }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="handleQuery"
              />
            </el-card>
          </el-splitter-panel>
          <el-splitter-panel :size="200">
            <el-card shadow="never">
              {{ $t("location.filter") }}
              <el-tree
                ref="treeRef"
                class="flat-tree"
                :data="locationList"
                size="90%"
                show-checkbox
                check-strictly
                default-expand-all
                :default-checked-keys="defaultCheckedKeys"
                node-key="id"
                highlight-current
                :props="defaultProps"
                @check-change="handleNodeClick"
              />
            </el-card>
          </el-splitter-panel>
        </el-splitter>

        <el-dialog
          v-model="dialog.visible"
          :title="dialog.title"
          :width="dialogWidth"
          @close="handleCloseDialog"
        >
          <el-scrollbar v-loading="xloading" height="300px" :always="true">
            <div v-if="timelineData.length > 0">
              <el-steps direction="vertical" :space="85" :active="10000">
                <el-step
                  v-for="(item, index) in timelineData.slice().reverse()"
                  :key="index"
                  :icon="CustomStepIconBuilder(timelineData.length - index)"
                  :title="item.name"
                >
                  <template #title>
                    <div>
                      <el-text
                        v-if="locationMap?.get(item.localId) == 1"
                        style="font-weight: bold; color: red"
                        size="large"
                        type="danger"
                      >
                        <el-tag type="danger">
                          <el-icon color="red"><WarnTriangleFilled /></el-icon>
                          {{ item.name }} ({{ t("location.isForbid") }})
                        </el-tag>
                      </el-text>
                      <el-text
                        v-else
                        style="font-weight: bold; color: black"
                        size="large"
                        type="info"
                      >
                        {{ item.name }}
                      </el-text>
                    </div>
                  </template>
                  <template #description>
                    <div>
                      <el-text class="mx-1" size="small" type="primary">
                        {{
                          t("visitor.fromTime") +
                          ": " +
                          dayjs.unix(item.createdAt).format("YYYY-MM-DD HH:mm:ss")
                        }}
                      </el-text>
                    </div>
                    <div>
                      <el-text class="mx-1" size="small" type="danger">
                        {{
                          item.updatedAt == null
                            ? ""
                            : t("visitor.lastTime") +
                              ": " +
                              dayjs.unix(item.updatedAt).format("YYYY-MM-DD HH:mm:ss")
                        }}
                      </el-text>
                    </div>
                  </template>
                </el-step>
              </el-steps>
            </div>
            <div v-else align-middle>
              <e-text type="info">{{ $t("visitor.noVisitLine") }}</e-text>
            </div>
          </el-scrollbar>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="handleCloseDialog">{{ $t("common.cancel") }}</el-button>
            </div>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
    <el-drawer v-model="showDrawer" :title="$t('location.name')" :with-header="true">
      <el-tree
        ref="treeRef"
        :data="locationList"
        size="90%"
        show-checkbox
        check-strictly
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        highlight-current
        :props="defaultProps"
        @check-change="handleNodeClick"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmDrawer">
            {{ $t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "VisitorInviteList",
  inheritAttrs: false,
});

const xloading = ref(false);
import CustomStepIcon from "./CustomStepIcon.vue";
import VisitorAPI, { IPageQuery, InvitePageVO, VisitorLocationVo } from "@/api/visitor/index";
import LocationAPI, { LocationTree } from "@/api/location/index";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);

const treeRef = ref<InstanceType<typeof ElTree>>();
const defaultCheckedKeys = ref<any[] | undefined>([]);

const loading = ref(false);
const total = ref(0);
const locationList = ref<LocationTree[]>();
const showDrawer = ref(false);

const queryParams = reactive<IPageQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  localIds: [],
  statuses: ["1"],
  startTime: "",
  endTime: "",
});

const timelineData = ref();

const list = ref<InvitePageVO[]>();
const tableData = ref<any[]>([]);

const locationMap = ref<Map<number, number>>();

const dialog = reactive({
  title: "",
  visible: false,
});

let stopListInterval = setInterval(() => {
  handleQuery();
}, 30000);

function handleShowDrawer() {
  //showDrawer.value = true;
}
function confirmDrawer() {
  showDrawer.value = false;
  getCheckedNodes();
}

function handleQuery() {
  //loading.value = true;
  VisitorAPI.getCurrentVisitorsList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
  getLocations(queryParams);
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function showMovedLine(id: number) {
  dialog.visible = true;
  dialog.title = t("visitor.movedLine");
  getVisitorMovelines(id);
}

function getVisitorMovelines(id: number) {
  xloading.value = true;
  timelineData.value = [];
  VisitorAPI.getVisitorLocationList(id)
    .then((data) => {
      const responses: VisitorLocationVo[] = Object.assign(data);
      responses.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
      timelineData.value = responses;
    })
    .finally(() => {
      loading.value = false;
      xloading.value = false;
    });
}

function handleCloseDialog() {
  dialog.visible = false;
}

function getLocations(queryParams: IPageQuery) {
  LocationAPI.getRealLocations(queryParams).then((res) => {
    locationList.value = res;
  });
}

function getAllLocations() {
  LocationAPI.getList()
    .then((res) => {
      tableData.value = res.map((row: any) => ({
        localId: row.localId,
        isForbid: row.isForbid,
      }));

      const map = new Map<number, number>();
      tableData.value.forEach((item) => {
        map.set(item.localId, item.isForbid);
      });
      locationMap.value = map;
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  getAllLocations();
  handleQuery();
});

onUnmounted(() => {
  clearInterval(stopListInterval);
});

const getCheckedNodes = () => {
  const selectedNodes = treeRef.value?.getCheckedNodes();
  defaultCheckedKeys.value = selectedNodes?.map((item) => item.id);
  queryParams.localIds = selectedNodes?.map((item) => item.id);
  handleQuery();
};
function handleNodeClick() {
  getCheckedNodes();
}

function handleLeft(id: number) {
  ElMessageBox.confirm(t("visitor.confirmLeft"), t("visitor.leftTip"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(() => {
    loading.value = true;
    VisitorAPI.unbindTag(id)
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success(res.data.message);
          handleResetQuery();
        } else {
          ElMessage.error(res.data.message);
        }
      })
      .finally(() => (loading.value = false));
  });
}
const CustomStepIconBuilder = (label: number) => {
  return h(CustomStepIcon, { label });
};
const defaultProps = {
  children: "children",
  label: "label",
};
</script>
<style scoped>
:deep(.flat-tree .el-tree-node__expand-icon) {
  display: none !important;
}

:deep(.flat-tree .el-tree-node__content > .el-tree-node__icon) {
  display: none !important;
}

:deep(.flat-tree .el-tree-node) {
  margin-left: 0 !important;
}

:deep(.flat-tree .el-tree-node__content) {
  padding-left: 0 !important;
}
:deep(.el-step.is-vertical .el-step__main) {
  margin-top: 4px !important;
}
</style>
